package net.forsalemall.android;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.TextDrawable;
import com.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class UploadAds extends Activity {
	private View images;
	private TextView noticeView;
	private EditText adTextField;
	private EditText phoneNoField;
	private Spinner superCatSpinner;
	private Spinner catSpinner;
	private View.OnLongClickListener longClickListener;
	private List<Bitmap> bitmaps;
	private List<File> files;

	private Uri imageUri;
	private int counter = 0;
	private static final int GET_IMAGE_FROM_GALLERY = 0;
	private static final int GET_IMAGE_BY_CAMERS = 1;

//	private List<ListItem> catItems;
	private HashMap<String, ListItem> catItems;
	private List<String> catLabels;
	private List<String> superCatLabels;

	private String superCategoryData;
	private JSONArray jSuperCategories;
	private String countryCode;
	private String phoneNo;
	private int postType;
	private int remAdPosting;
	private int phoneNoLength;
	private String phonePrefix;
	

	private Map<String, JSONArray> categoris;

	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.upload_ad);
			final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getString(R.string.title_post_ads));
			countryCode = getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE);
			phoneNo = getIntent().getStringExtra(Constants.KEY_PHONE_NO);
			remAdPosting = 0;
			catItems = new HashMap<String, ListItem>();
			catLabels = new ArrayList<String>();
			superCatLabels = new ArrayList<String>();
			categoris = new HashMap<String, JSONArray>();
			actionBar.setHomeAction(new Action() {

				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});
			actionBar.setDisplayHomeAsUpEnabled(true);

			findViewById(R.id.button_pick_by_camera).setOnClickListener(
					new View.OnClickListener() {
						public void onClick(View v) {
							takePicture();
						}
					});
			findViewById(R.id.button_pick_from_gallery).setOnClickListener(
					new View.OnClickListener() {
						public void onClick(View v) {
							pickFromGallery();
						}
					});

			noticeView = (TextView) findViewById(R.id.notice_view);
			adTextField = (EditText) findViewById(R.id.ad_text_field);
			phoneNoField = (EditText) findViewById(R.id.phone_no_field);

			phonePrefix = Constants.COUNTRY_CODE_KUWAIT.equals(countryCode) ? Constants.PHONE_CODE_KUWAIT
					: Constants.PHONE_CODE_UAE;
			phoneNoLength = Constants.COUNTRY_CODE_KUWAIT.equals(countryCode) ? Constants.NUMBER_OF_PHONE_DIGIT_KUWAIT
					: Constants.NUMBER_OF_PHONE_DIGIT_UAE;
			TextDrawable td = new TextDrawable(phonePrefix + "-");
			td.setTextSize(phoneNoField.getTextSize());
			phoneNoField.setCompoundDrawablesWithIntrinsicBounds(td, null,
					null, null);
			int phoneDigit = Constants.COUNTRY_CODE_KUWAIT.equals(countryCode) ? Constants.NUMBER_OF_PHONE_DIGIT_KUWAIT
					: Constants.NUMBER_OF_PHONE_DIGIT_UAE;
			InputFilter[] FilterArray = new InputFilter[1];
			FilterArray[0] = new InputFilter.LengthFilter(phoneDigit);
			phoneNoField.setFilters(FilterArray);
			if ((phoneNo != null) && (phoneNo.length() > phonePrefix.length())
					&& (phoneNo.startsWith(phonePrefix))) {
				phoneNoField.setText(phoneNo.substring(phonePrefix.length()));
			} else {
				phoneNoField.setText("");
			}

			// adTextField.setText("كيف حالك؟");

			images = findViewById(R.id.images_container);
			bitmaps = new ArrayList<Bitmap>();
			files = new ArrayList<File>();
			findViewById(R.id.button_sumit).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							submit();
						}
					});
			findViewById(R.id.button_reset).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							reset();
						}
					});

			longClickListener = new View.OnLongClickListener() {

				public boolean onLongClick(View view) {
					final View v = view;
					AlertDialog.Builder bb = new AlertDialog.Builder(
							UploadAds.this);
					bb.setMessage(getString(R.string.delete_confirmation_message));
					bb.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									removeImage(v);
								}
							});
					bb.setNegativeButton(getString(R.string.no),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
								}
							});
					bb.show();
					return true;
				}
			};
			images.findViewById(R.id.image_item1).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item2).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item3).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item4).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item5).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item6).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item7).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item8).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item9).setOnLongClickListener(
					longClickListener);
			superCatSpinner = (Spinner) findViewById(R.id.super_category_spinner);
			catSpinner = (Spinner) findViewById(R.id.category_spinner);
			superCatSpinner
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						public void onItemSelected(AdapterView<?> av, View v,
								int position, long arg3) {
							Log.i("DREG", "POS=" + position);
							superCatSelected(position-1);

						}

						public void onNothingSelected(AdapterView<?> arg0) {
							superCatSelected(-1);

						}
					});
			showImages();
//			showPostTypeOptions();
			postType = Constants.TYPE_NORMAL_CAT;
			calculateRemainingAd();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showPostTypeOptions() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.posted_options))
				.setCancelable(true)
				.setOnCancelListener(new DialogInterface.OnCancelListener() {
					public void onCancel(DialogInterface dialog) {
						finish();
					}
				})
				.setPositiveButton(getString(R.string.for_sale),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								postType = Constants.TYPE_NORMAL_CAT;
								calculateRemainingAd();
							}
						})
				.setNegativeButton(getString(R.string.service),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								postType = Constants.TYPE_FEATURE_CAT;
								calculateRemainingAd();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void calculateRemainingAd() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;
			private Exception exception = null;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(UploadAds.this,
							null, getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					String resp = HttpUtils.getAdPostedCountInPeriod(Utils
							.getDeviceId(UploadAds.this));
//					remAdPosting = Constants.MAX_NUMBER_OF_CAN_BE_POST_IN_CYCLE
//							- (new JSONObject(resp)).getInt("c");
					remAdPosting = Constants.getMaxPostInMonth()
					- (new JSONObject(resp)).getInt("c");
					if (remAdPosting > 0) {
						if (postType == Constants.TYPE_FEATURE_CAT) {
							superCategoryData = HttpUtils
									.getServiceCategoriesData(countryCode);
						} else {
							superCategoryData = HttpUtils
									.getForsaleCategoriesData(countryCode);
						}

						jSuperCategories = new JSONArray(superCategoryData);
						if (jSuperCategories != null) {
							JSONObject jo;
							String label;
							superCatLabels.add(getString(R.string.please_select_a_category));
							for (int i = 0; i < jSuperCategories.length(); i++) {
								jo = jSuperCategories.getJSONObject(i);
								label = Utils.getDecodedString(jo
										.getString("sup_cat_name"));
								superCatLabels.add(label);
								categoris.put(Integer.toString(i),
										jo.getJSONArray("categories"));
							}
						}
					}

				} catch (Exception e) {
					exception = e;
					e.printStackTrace();
				}
				return null;
			}

			@SuppressWarnings({ "unchecked", "rawtypes" })
			protected void onPostExecute(String unused) {
				try {
					progressDialog.dismiss();
					if(exception==null){
					if (remAdPosting > 0) {
						// loadCategories();
						ArrayAdapter adapter = new ArrayAdapter(UploadAds.this,
								android.R.layout.simple_spinner_item,
								superCatLabels);
						adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						superCatSpinner.setAdapter(adapter);
						if (superCatLabels.size() > 0) {
							superCatSpinner.setSelection(0);
						}
					} else {
						showPostingLimitFinishMessage();
					}
					}else{
						showPostingLimitErrorMessage(exception.getMessage());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void showPostingLimitErrorMessage(String errorMessage) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(errorMessage)
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								finish();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}
	private void showPostingLimitFinishMessage() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.ad_limit_finished))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								finish();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void adDuplicateMessage() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.message_duplicate_ad))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								finish();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void adPostedMessage() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(
				String.format(getString(R.string.ad_posted),
						Integer.toString(remAdPosting)))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								finish();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void submit() {
		try {
			String text = adTextField.getText().toString();
			if (files.size() < Constants.MIN_IMAGES) {
				Utils.showAlertMessage(this, null,
						getString(R.string.no_image_attached));
			} else if (text.length() == 0) {
				Utils.showAlertMessage(this, null,
						getString(R.string.no_text_attached));
			} else if (phoneNoField.length() != phoneNoLength) {
				Utils.showAlertMessage(this, null,
						getString(R.string.enter_valid_phone_no));
			}  else if((catSpinner.getAdapter().getCount()==0) ||(catSpinner.getSelectedItemPosition()==0)){
				Utils.showAlertMessage(this, null,
						getString(R.string.please_select_a_subcategory));
			}
			else {
//				String catName = (String)catSpinner.getSelectedItem();
				submit(text,
						catItems.get(catSpinner.getSelectedItem()).catId,
						(phonePrefix + (phoneNoField.getText().toString())));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void submit(final String text, final int catId, final String phNo)
			throws Exception {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;
			private String error;
			private String resp;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(UploadAds.this,
							null, getString(R.string.loading));
					progressDialog.show();
					error = null;
				} catch (Exception e) {
					error = e.getMessage();
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					String fileNames = "";
					JSONObject jo;
					for (int i = 0; i < files.size(); i++) {
						jo = new JSONObject(HttpUtils.uploadImageFile(files
								.get(i)));
						if (i == 0) {
							fileNames = jo.getString("fn");
						} else {
							fileNames += "|" + jo.getString("fn");
						}
					}

					resp = HttpUtils.postAd(Utils.getDeviceId(UploadAds.this), text,
							postType, catId, countryCode, phNo, fileNames);
					// JSONObject jAd = new JSONObject(adData);
					// HttpUtils.attachFiles(jAd.getInt("ad_id"), fileNames);

				} catch (Exception e) {
					error = e.getMessage();
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					progressDialog.dismiss();
					if (error == null) {
						JSONObject jo = new JSONObject(resp);
						if((!jo.isNull("e")) && (jo.getInt("e")==0)){
							reset();
							remAdPosting--;
							if (remAdPosting > 0) {
								adPostedMessage();
							} else {
								showPostingLimitFinishMessage();
							}
						}else{
							 adDuplicateMessage();
						}
						
					} else {
						Utils.showAlertMessage(UploadAds.this, null, error);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void reset() {
		try {
			bitmaps.clear();
			files.clear();
			adTextField.setText("");
			superCatSpinner.setSelection(0);
			catSpinner.setSelection(0);
			showImages();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void superCatSelected(int index) {
		try {
			catLabels.clear();
			catItems.clear();
			if (index >= 0 && index < categoris.size()) {

				JSONArray jCategories = categoris.get(Integer.toString(index));

				if (jCategories != null) {
					JSONObject jo;
					String label;
					catLabels.add(getString(R.string.please_select_a_subcategory));
					for (int i = 0; i < jCategories.length(); i++) {
						jo = jCategories.getJSONObject(i);
						label = Utils
								.getDecodedString(jo.getString("cat_name"));
						catLabels.add(label);
						catItems.put(label, new ListItem(jo.getInt("cat_id"), label));
//						catItems.add(new ListItem(jo.getInt("cat_id"), label));
					}
				}
			}
			ArrayAdapter adapter = new ArrayAdapter(UploadAds.this,
					android.R.layout.simple_spinner_item, catLabels);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			catSpinner.setAdapter(adapter);
			if (catLabels.size() > 0) {
				catSpinner.setSelection(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void removeImage(final View view) {
		switch (view.getId()) {
		case R.id.image_item1:
			bitmaps.remove(0);
			files.remove(0);
			break;
		case R.id.image_item2:
			bitmaps.remove(1);
			files.remove(1);
			break;
		case R.id.image_item3:
			bitmaps.remove(2);
			files.remove(2);
			break;
		case R.id.image_item4:
			bitmaps.remove(3);
			files.remove(3);
			break;
		case R.id.image_item5:
			bitmaps.remove(4);
			files.remove(4);
			break;
		case R.id.image_item6:
			bitmaps.remove(5);
			files.remove(5);
			break;
		case R.id.image_item7:
			bitmaps.remove(6);
			files.remove(6);
			break;
		case R.id.image_item8:
			bitmaps.remove(7);
			files.remove(7);
			break;
		case R.id.image_item9:
			bitmaps.remove(8);
			files.remove(8);
			break;
		default:
			break;
		}
		showImages();
	}

	private void showImages() {
		ImageView imView = null;
		for (int i = 0; i < Constants.MAX_IMAGES; i++) {
			switch (i) {
			case 0:
				imView = (ImageView) images.findViewById(R.id.image_item1);
				break;
			case 1:
				imView = (ImageView) images.findViewById(R.id.image_item2);
				break;
			case 2:
				imView = (ImageView) images.findViewById(R.id.image_item3);
				break;
			case 3:
				imView = (ImageView) images.findViewById(R.id.image_item4);
				break;
			case 4:
				imView = (ImageView) images.findViewById(R.id.image_item5);
				break;
			case 5:
				imView = (ImageView) images.findViewById(R.id.image_item6);
				break;
			case 6:
				imView = (ImageView) images.findViewById(R.id.image_item7);
				break;
			case 7:
				imView = (ImageView) images.findViewById(R.id.image_item8);
				break;
			case 8:
				imView = (ImageView) images.findViewById(R.id.image_item9);
				break;
			default:
				break;
			}
			if (i < bitmaps.size()) {
				imView.setImageBitmap(bitmaps.get(i));
			} else {
				imView.setImageBitmap(null);
			}
		}
		if (bitmaps.size() > 0) {
			noticeView.setVisibility(View.GONE);
		} else {
			noticeView.setVisibility(View.VISIBLE);
		}
	}

	private void takePicture() {
		if (files.size() < Constants.MAX_IMAGES) {
//			String fileName = Integer.toString(counter++);
//			ContentValues values = new ContentValues();
//			values.put(MediaStore.Images.Media.TITLE, fileName);
//			values.put(MediaStore.Images.Media.DESCRIPTION,
//					"Image capture by camera");
//			imageUri = getContentResolver().insert(
//					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//			
//			startActivityForResult(intent, GET_IMAGE_BY_CAMERS);
			
			String fileName = Integer.toString(counter++);
			ContentValues values = new ContentValues();
			values.put(MediaStore.Images.Media.TITLE, fileName);
			values.put(MediaStore.Images.Media.DESCRIPTION,
					"Image capture by camera");
			imageUri = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(intent, GET_IMAGE_BY_CAMERS);
		} else {
			Utils.showAlertMessage(this, null,
					getString(R.string.image_constraint_message));
		}
	}

	private void pickFromGallery() {
		if (files.size() < Constants.MAX_IMAGES) {
			
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);

			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					GET_IMAGE_FROM_GALLERY);
			
//			Intent intent = new Intent();
//			intent.setType("image/*");
//			intent.setAction(Intent.ACTION_GET_CONTENT);
//			startActivityForResult(
//					Intent.createChooser(intent, "Select Picture"),
//					GET_IMAGE_FROM_GALLERY);
		} else {
			Utils.showAlertMessage(this, null,
					getString(R.string.image_constraint_message));
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		Bitmap image = null;
		File file = null;
		String path = null;
		int imgWidth = (2 * getWindowManager().getDefaultDisplay().getWidth()) / 5;
		switch (requestCode) {
		case GET_IMAGE_BY_CAMERS:
			
			try {
				if (data == null) {
					file = Utils.convertImageUriToFile(imageUri,
							getApplicationContext());
				} else {
					file = Utils.convertImageUriToFile(data.getData(),
							getApplicationContext());
				}
				image = Utils.decodeFile(file, imgWidth, imgWidth);
			} catch (Exception e) {
				Log.i("DREG", Utils.getException(e));
				e.printStackTrace();
			}
//			try {
//				
//				file = Utils.convertImageUriToFile(imageUri, UploadAds.this);
//				path = file.getAbsolutePath();
//				image = Utils.decodeFile(file, imgWidth, imgWidth);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}

			break;
		case GET_IMAGE_FROM_GALLERY:
			try {
				Uri selectedImageUri = data.getData();
				file = new File(Utils.getPath(getApplicationContext(),
						selectedImageUri));
				image = Utils.decodeFile(file, imgWidth, imgWidth);
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), e.toString(),
						Toast.LENGTH_LONG).show();
			}
//
//			try {
//				Uri selectedImageUri = data.getData();
//				file = new File(Utils.getRealPathFromURI(selectedImageUri,
//						UploadAds.this));
//				path = file.getAbsolutePath();
//				image = Utils.decodeFile(file, imgWidth, imgWidth);
//
//			} catch (Exception e) {
//
//				Toast.makeText(getApplicationContext(), e.toString(),
//						Toast.LENGTH_LONG).show();
//			}
			break;
		default:
			break;
		}
		if (image == null || file == null) {
			return;
		} else {
			bitmaps.add(image);
			files.add(file);
			showImages();
		}
	}

	class ListItem {
		private String title;
		private int catId;

		public ListItem(int catId, String title) {
			this.catId = catId;
			this.title = title;
		}

		public int getCatId() {
			return catId;
		}

		public String getTitle() {
			return title;
		}
	}
}
